'use strict';
const oauth2orize = require('oauth2orize');
const passport = require('passport');
const BearerStrategy = require('passport-http-bearer').Strategy;
passport.use(new BearerStrategy(function(accessToken, done) {
    //1. 查询db，token是否已经被销毁
    //2.校验token完整性，时效性
    if (accessToken) {
        done(null, true);
    } else {
        done(null, false);
    }
}));
exports.authenticate = function() {
    return function(req, res, next) {
        passport.authenticate('bearer', function(err, user, info) {
            if (err) return next(err);
            if (!user) {
                //res.status(401).end('Unauthorized:' + info.message);
            }
            req.user = user;
            next();
        })(req, res, next);
    }
};
//=====================================================================
const server = oauth2orize.createServer();
server.exchange(oauth2orize.exchange.password(function(client, username, password, scope, done) {
    if (username === 'gay' && password === '123') {
        done(null, 'this is token', 'this is refreshToken', {
            expires_in: 3600,
            token_type: 'Bearer'
        });
    }else {
        done(null,false);
    }
}));
server.exchange(oauth2orize.exchange.refreshToken(function(client, refreshToken, scope, done) {
    //1. 查db，refreshToken是否被销毁
    //2. 校验完整性，时效性
    //3. 重新生成access_token
    //4. 替换掉老的access_token
    if(refreshToken){
        done(null,"this is access_token");
    }else {
        done(null,false);
    }
}));

exports.token = [
    server.token(),
    server.errorHandler()
]